#conding:utf-8
import requests
import json
import threading
import csv
import time

# 将请求的数据, 转换成json数据
def get_true_json(conn, key=False):
    index = conn.find('(') + 1
    conn = conn[index:-2]

    if not key:
        return conn
    else:
        return json.loads(conn, encoding='utf-8')

# 获取音乐数据
def get_data_json():
    data_url = 'https://searchrecommend.kugou.com/get/complex?callback=jQuery1124027331113823236675_1559647295775&word=%E5%86%AF%E6%8F%90%E8%8E%AB&_=1559647295778'

    conn = requests.get(url=data_url)

    conn.encoding='utf-8'
    conn = get_true_json(conn.text)
    with open('data.json', 'w', encoding='utf-8') as f:
        f.write(conn)

    jsonStr = json.loads(conn)

    print(jsonStr)

# 保存 list 为csv文件
def save_csv(list_li):
    thLock = threading.Lock()
    thLock.acquire()
    f = open('music_url.csv', 'a+', encoding='utf-8', newline='')
    writer = csv.writer(f)
    writer.writerow(list_li)
    f.close()
    thLock.release()

# 保存歌词文件
def save_lyric(name, words):
    thLock = threading.Lock()
    type = '.lrc'
    path = 'lyric/'
    thLock.acquire()
    if words == '':
        return

    if '' == name:
        name = str(int(time.time()))
    abspath = path + name + type

    f = open(abspath, 'w', encoding='utf-8')
    f.write(words)
    f.close()
    thLock.release()

# 打印json数据
def json_print():
    with open('data.json', 'r', encoding='utf-8') as f:
        jsonStr = json.load(f)
        music_lists = jsonStr[0]['data']['song']
        for i in music_lists:
            print('hash : ', i.get('hash'), 'albumID : ', i.get('AlbumID'))
            print(i.get('songname'), '--', i.get('singername'))
            hash = i.get('hash')
            AlbumID = str(i.get('AlbumID'))
            url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19108399584051974596_1559657369369&hash=%s&' \
                  'album_id=%s&' \
                  'dfid=3v4sCD1xdbzr0AaEpN1hUKUI&mid=08f708b454f6ffe7fc8e7d6a2580580d&platid=4&_=1559657369370' % (hash, AlbumID)
            conn = requests.get(url=url)
            conn.encoding='utf-8'
            conn = get_true_json(conn.text, True)
            data = conn['data']
            audio_name = data.get('audio_name')
            author_name = data.get('author_name')
            song_name = data.get('song_name')
            play_url = data.get('play_url')
            lyrics = data.get('lyrics')

            print([audio_name, author_name, song_name, play_url, lyrics])
            save_csv([audio_name, author_name, song_name, play_url])
            save_lyric(audio_name, lyrics)
            time.sleep(5)

json_print()